<html lang='zh-CN'>
<head>
<meta charset='utf-8'>
	<style>
		.container {
			position: relative;
			float: left;
		}
		
		.box {
			width: 400px;
			height: 400px;
			border: 2px solid black;
			background-image: url(img/1.jpg);
			background-position: center;
			background-repeat:no-repeat;
		}
		
		
		.canvas {
			display: none;
			width: 300px;
			height: 300px;
			background-color: red;
			opacity: 0.4;
			position: relative;
			cursor: move;
		}
		
		.magnify {
			display: none;
			width: 732px;
			height: 450px;
			position: absolute;
			left: 410px;
			top: 0;
			border: 2px solid yellow;
			background-color:red;
		}
		
		.magnify img {
			position: relative;
			width: 100%;
			height: 100%;
		}
		
	</style>
	
</head>

<body>
	<div class='container'>
		<div class='box'>
			<div class='canvas'></div>
		</div>
		<div class='magnify'><img src='img/1.jpg'></div>
	</div>
</body>
<script>
// box套canvas canvas不移出box且鼠标位于canvas中心，右边显示放大图片
// move canvas mask
	var box = document.querySelector('.box');
	var canvas = document.querySelector('.canvas');
	var img = document.querySelector('img');
	var magnify = document.querySelector('.magnify')
	box.addEventListener('mousemove',function(e){
	// 以box大容器为位置参考，得出鼠标与box的相对位置
		var x = e.pageX - box.offsetLeft;
		var y = e.pageY - box.offsetTop;
	// 相对鼠标移动canvas，使得鼠标位于canvas中间	
		var cx = x - box.offsetWidth/2;
		var cy = y - box.offsetHeight/2;
	// 定位只有top left两个方位，所以用box宽度 - canvas宽度得出在left canvas距离box的距离上限从而限制canvas移出box
		var xMax = box.offsetWidth - canvas.offsetWidth;
		var yMax = box.offsetHeight - canvas.offsetHeight;
		if ( cx<=0 ) cx=0;
		else if ( cx>=xMax ) cx=xMax;
		
		if ( cy<=0 ) cy=0;
		else if ( cy>=yMax ) cy=yMax;
		
		canvas.style.top = cy + 'px';
		canvas.style.left = cx + 'px';
		
		canvas.style.display = 'block';
		
		// move image
		magnify.style.display = 'block';
	// 也是算出可移动上限
		var myMax = magnify.offsetHeight-img.offsetHeight;
		var mxMax = magnify.offsetWidth-img.offsetWidth;
	// 计算canvas可移动上限与magnify可移动上限的比例从而得出两者的移动距离比例，实现同步，注意需要去符号移动方向取反
		img.style.top = -cy*myMax / yMax + 'px';
		img.style.left = -cx* mxMax / xMax+ 'px';
		
	})
	
	
	
	
</script>
</html>